﻿using B.S.DataBase.MyProject.Domain.ChronicDiseaseManagement;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure;
using MediatR;
using MedicalPCTerminal.Read.API.Appcation.Commands.ChronicCare;

namespace MedicalPCTerminal.Read.API.Appcation.CommandHandlers.ChronicCare
{
    /// <summary>
    /// 查询复诊计划命令处理方法
    /// </summary>
    public class QueryFollowUpPlanCommandHandler:IRequestHandler<QueryFollowUpPlanCommand,APIResult<List<FollowUpPlan>>>
    {
        /// <summary>
        /// sqlsugar
        /// </summary>
        private readonly SqlSugarContext sugar;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sugar"></param>
        public QueryFollowUpPlanCommandHandler(SqlSugarContext sugar)
        {
            this.sugar = sugar;
        }

        /// <summary>
        /// 查询复诊计划
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<List<FollowUpPlan>>> Handle(QueryFollowUpPlanCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<FollowUpPlan>> result = new APIResult<List<FollowUpPlan>>();
            try
            {
                var list = sugar.db.Queryable<FollowUpPlan>();
                if (request.ResidentFiles_Id!=null)
                {
                    list = list.Where(x => x.ResidentFiles_Id == request.ResidentFiles_Id);
                }
                list = list.OrderByDescending(x => x.FollowUpPlanId);
                result.data = list.ToList();
                result.Code = APIEnum.查询成功;
                result.Msg = APIEnum.查询成功.ToString();
            }
            catch (Exception ex)
            {

                // 记录异常信息
                Console.WriteLine($"查询复诊计划时发生异常: {ex.Message}");
                result.Code = APIEnum.查询失败;
                result.Msg = APIEnum.查询失败.ToString();
            }
            return await Task.FromResult(result);
        }


    }

}
